const db = require('../config/db');

// Add a new consumption record for a check-in
exports.addConsumption = async (req, res) => {
    try {
        const { checkin_id, item_id, quantity } = req.body;

        // Fetch item details (name and price) from menu_items table
        const [menuItem] = await db.query('SELECT item_name, price FROM menu_items WHERE item_id = ?', [item_id]);
        if (menuItem.length === 0) {
            return res.status(400).json({ error: '菜单项不存在' });
        }

        const { item_name, price } = menuItem[0];
        const amount = quantity * price; // Calculate total amount for this consumption

        // Insert into Consumptions table
        const [result] = await db.query(
            'INSERT INTO Consumptions (checkin_id, item_name, quantity, amount, consume_time) VALUES (?, ?, ?, ?, NOW())',
            [checkin_id, item_name, quantity, amount]
        );

        // Update total_amount in Checkins table
        await db.query(
            'UPDATE Checkins SET total_amount = COALESCE(total_amount, 0) + ? WHERE checkin_id = ?',
            [amount, checkin_id]
        );

        res.status(201).json({ message: '消费记录添加成功', consumptionId: result.insertId });
    } catch (err) {
        console.error('添加消费记录错误:', err);
        res.status(500).json({ error: '添加消费记录失败', details: err.message });
    }
};

// Get all consumptions for a specific check-in
exports.getConsumptionsByCheckin = async (req, res) => {
    try {
        const { checkinId } = req.params;
        const [rows] = await db.query(
            `SELECT
                 consumption_id,
                 checkin_id,
                 item_name,  -- Use item_name directly from Consumptions
                 quantity,
                 amount,
                 consume_time
             FROM Consumptions
             WHERE checkin_id = ?
             ORDER BY consume_time DESC`,
            [checkinId]
        );
        res.status(200).json(rows);
    } catch (err) {
        console.error('获取入住消费记录错误:', err);
        res.status(500).json({ error: '获取入住消费记录失败', details: err.message });
    }
};

// Get consumption records by guest ID card (for client-side usage)
exports.getConsumptionsByGuestCard = async (req, res) => {
    try {
        const { idCard } = req.params;
        const [rows] = await db.query(
            `SELECT
                 con.consumption_id,
                 con.checkin_id,
                 con.item_name,
                 con.quantity,
                 con.amount,
                 con.consume_time,
                 r.room_number,
                 g.name AS guest_name
             FROM Consumptions con
                      JOIN Checkins c ON con.checkin_id = c.checkin_id
                      JOIN Guests g ON c.guest_id = g.guest_id
                      JOIN Rooms r ON c.room_id = r.room_id
             WHERE g.id_card = ?
             ORDER BY con.consume_time DESC`,
            [idCard]
        );
        res.status(200).json(rows);
    } catch (err) {
        console.error('根据身份证查询消费记录错误:', err);
        res.status(500).json({ error: '获取消费记录失败', details: err.message });
    }
};